package com.ymatou.apigateway.testcase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.ymatou.apigateway.parameter.AesUtil;
import com.ymatou.apigateway.parameter.OpenapiReq;
import com.ymatou.apigateway.parameter.SkuStock;
import com.ymatou.apigateway.parameter.V1updateproductstockBean;
import com.ymatou.apigateway.service.OpenapiService;
import com.ymatou.apigateway.service.ShenqiUpdateProductStockCall;
import com.shop2cn.iapi.agentproducts.parameter.DetailsCatalogDto;
import com.shop2cn.iapi.agentproducts.parameter.ProductDetailsDto;
import com.ymt.core.tool.FormatUtil;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AddAgentProductCallService;
import com.ymttest.business.service.GodProductStockCallService;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.model.Application;
import com.ymttest.database.model.AuthCode;
import com.ymttest.database.model.YmtCatalogsI;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.CatalogsWapper;
import com.ymttest.database.sqlwapper.OpenApiWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/**
*更新商品库存
*FreeMaker Template自动生成代码
*/
@TestSuite
public class Ts_sqUpdateProductStock {

	private static OpenapiReq openapiReq;
	private static V1updateproductstockBean v1updateproductstockBean;
	private static ShenqiUpdateProductStockCall shenqiUpdateProductStockCall;
	
	private static long autotest_goodsOwnerId = ShenqiUserSet.autotest_goodsOwnerId;
	private static long multiCDFCodeGoodsOwnerId = ShenqiUserSet.multiCDFCodeGoodsOwnerId;
	
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("更新神器商品库存");
	}

	@Before
	public void caseUp() {
		openapiReq = new OpenapiReq();
		openapiReq.setMethod("sq.sku.stock.update");

		v1updateproductstockBean = new V1updateproductstockBean();
		shenqiUpdateProductStockCall = new ShenqiUpdateProductStockCall();
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult(shenqiUpdateProductStockCall.getOpurl());
	}

	@After
	public void caseDown() {
		Logger.end();
	}
	
	public static void setSkuForAddProduct(List<String> skuList,
			JSONObject addProdRequest) throws JSONException {
		JSONArray catalogAry = addProdRequest.getJSONObject("Product")
				.getJSONArray("Catalogs");
		int minNum = Math.min(skuList.size(), catalogAry.length());
		for (int i = 0; i < minNum; i++) {
			catalogAry.getJSONObject(i).put("SKU", skuList.get(i));
		}
	}

	public static List<String> generateSKUList(int num) {
		List<String> skuList = new ArrayList<>();
		for (int i = 0; i < num; i++) {
			skuList.add("SKU" + TestDataManager.getRandomIntNum(10));
		}
		return skuList;
	}

	public static Map<String, Object> generateSKUStock(List<String> skuList) {
		
		Map<String, Object> retMap = new HashMap<>();
		
		skuList.forEach(ele -> {
			int stock = TestDataManager.getRandomIntNum(2);
			retMap.put(ele, stock);
			Logger.comment("SKU: " + ele + ", stock: " + stock);
		});
		
		return retMap;
	}

	private void checkStockBySku(JSONArray skuResults,
			Map<String, Object> skuIdandStockMap) throws Exception {
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();

		for (String skuId : skuIdandStockMap.keySet()) {
			// 返回报文检查
			boolean isFoundInRet = false;
			for (int j = 0; j < skuResults.length(); j++) {
				if (skuResults.getJSONObject(j).getString("sku_id")
						.equals(skuId)) {
					Logger.verifyEquals(true, skuResults.getJSONObject(j)
							.getBoolean("success"), "ExecSuccess 返回报文检查");

					isFoundInRet = true;
					break;
				}
			}
			Logger.verifyEquals(true, isFoundInRet, "SKU:" + skuId
					+ ",在返回报文中是否存在");

			YmtCatalogsI catalog = ymtCatalogsIWapper
					.selectCatalogsByCatalogId(skuId);
			// 期待库存
			int tgtStock = Integer.parseInt(skuIdandStockMap.get(skuId)
					.toString()) + catalog.getVirtualStock();

			String catalogId = catalog.getsCatalogId();
			int actStockInSql = Integer.parseInt(catalog.getiNum().toString());

			// sql
			Logger.verifyEquals(tgtStock, actStockInSql, "sql中库存检查 catalogId:"
					+ catalogId);

			String productId = catalog.getsProductId();

			// 手动同步库存
			GodProductStockCallService.sqCatalogStockChange_invokemongocrud(
					catalogId, productId);

			// java mongo
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()) {

				CatalogsWapper catalogsWapper = new CatalogsWapper();

				Map<String, Object> dataInMgo = catalogsWapper
						.getByCatalogId(catalogId);
				int actStockInMgo = Integer.parseInt(dataInMgo.get("stock")
						.toString());
				Logger.verifyEquals(tgtStock, actStockInMgo,
						"Java Mongo中库存检查 catalogId:" + catalogId);
			}
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_001() {
		Logger.start(true, "根据sku_id更新一品多码商品库存成功");
		try {
			
			AgentProductBean agentProductBean = DGSQBuildProxyChainCallService
					.createMultiCodeProxychain((int) multiCDFCodeGoodsOwnerId,
							false);
			//修改stock
			Map<String, Object> skuIdandStockMap = new HashMap<>();
			
			List<SkuStock> skuStocks = new ArrayList<SkuStock>();
			
			ProductDetailsDto selectProductDetails = AddAgentProductCallService
					.selectProductDetails((int) multiCDFCodeGoodsOwnerId,
							agentProductBean.getProductId());
			
			for (DetailsCatalogDto detailsCatalogDto : selectProductDetails.getCatalogList()) {
				try {
					
					SkuStock skuStock = new SkuStock();
					
					skuStock.setOuter_sku_id("outer" + detailsCatalogDto.getCatalogId());
					skuStock.setStock_num(100);
					skuStock.setSku_id(detailsCatalogDto.getCatalogId());
					skuStock.setSub_code_id(detailsCatalogDto.getSubCodeList().get(0).getCode());
					skuStock.setStock_operate(1);

					skuStocks.add(skuStock);
					
					skuIdandStockMap.put(detailsCatalogDto.getCatalogId(), 200);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(multiCDFCodeGoodsOwnerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();
			
			skuStocks.clear();
			
			for (DetailsCatalogDto detailsCatalogDto : selectProductDetails.getCatalogList()) {
				try {
					
					SkuStock skuStock = new SkuStock();
					
					skuStock.setOuter_sku_id("outer" + detailsCatalogDto.getCatalogId());
					skuStock.setStock_num(100);
					skuStock.setSku_id(detailsCatalogDto.getCatalogId());
					skuStock.setSub_code_id(detailsCatalogDto.getSubCodeList().get(0).getCode());
					skuStock.setStock_operate(2);

					skuStocks.add(skuStock);
					
					skuIdandStockMap.put(detailsCatalogDto.getCatalogId(), 200);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			v1updateproductstockBean.setSku_stocks(skuStocks);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			JSONObject retBean = new JSONObject(
					shenqiUpdateProductStockCall.getReturnData());

			Logger.verifyEquals("0000", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

			this.checkStockBySku(retBean.getJSONObject("content")
					.getJSONArray("results"), skuIdandStockMap);
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_002() {
		Logger.start(true, "更新商品库存-SkuId不存在");
		try {
			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			SkuStock skuStock = new SkuStock();
			//			skuStock.setOuter_sku_id("SKU966300381");
			skuStock.setStock_num(3);

			skuStocks.add(skuStock);

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(
							(long) Integer.parseInt(EnvSetup
									.getData("SellerId"))).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			Logger.verifyEquals("0001", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_003() {
		Logger.start(true, "更新商品库存-SkuId空");
		try {
			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			SkuStock skuStock = new SkuStock();
			//skuStock.setOuter_sku_id("SKU966300381");
			skuStock.setStock_num(3);

			skuStocks.add(skuStock);

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(
							(long) Integer.parseInt(EnvSetup
									.getData("SellerId"))).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			Logger.verifyEquals("0001", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

			Logger.verifyEquals("outer_sku_id 或 sku_id 必传一个.",
					shenqiUpdateProductStockCall.getMessage(), "验证message");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_004() {
		Logger.start(true, "更新商品库存-stock_num负数");
		try {
			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			SkuStock skuStock = new SkuStock();
			skuStock.setOuter_sku_id("SKU966300381");
			skuStock.setStock_num(-3);

			skuStocks.add(skuStock);

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(
							(long) Integer.parseInt(EnvSetup
									.getData("SellerId"))).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			Logger.verifyEquals("0001", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_005() {
		Logger.start(true, "更新商品库存-stock_num空");
		try {
			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			SkuStock skuStock = new SkuStock();
			skuStock.setOuter_sku_id("SKU966300381");

			skuStocks.add(skuStock);

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(
							(long) Integer.parseInt(EnvSetup
									.getData("SellerId"))).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			Logger.verifyEquals("0001", shenqiUpdateProductStockCall.getCode(),
					"验证Code");
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_006() {
		Logger.start(true, "更新他人商品库存");
		try {
			
			long sellerId = (long) Integer.parseInt(EnvSetup
					.getData("SellerId"));
			
			List<String> skuList = Arrays.asList("c2443405", "c2443404");

			//修改stock
			Map<String, Object> skuAndStockMap = generateSKUStock(skuList);

			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			for (String key : skuAndStockMap.keySet()) {
				try {
					SkuStock skuStock = new SkuStock();
					skuStock.setOuter_sku_id("outer" + key);
					skuStock.setStock_num(Integer.parseInt(skuAndStockMap.get(
							key).toString()));
					skuStock.setSku_id(key);

					skuStocks.add(skuStock);

				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			JSONObject retBean = new JSONObject(
					shenqiUpdateProductStockCall.getReturnData());

			Logger.verifyEquals("0000", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

			JSONArray jsonArray = retBean.getJSONObject("content")
					.getJSONArray("results");

			for (int j = 0; j < jsonArray.length(); j++) {

				Logger.verifyEquals(false, jsonArray.getJSONObject(j)
						.getBoolean("success"), "返回报文检查");
				Logger.verifyEquals("sku_id无效", jsonArray.getJSONObject(j)
						.getString("msg"), "返回报文msg检查");
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_007() {
		Logger.start(true, "根据sku_id更新中间商商品库存失败");
		try {
//			AgentProductBean agentProduct = DGSQBaseService.createProductByChain(
//					Arrays.asList(500002490L, 500004880L, 500004881L), true);
			
			long sellerId = (long) Integer.parseInt(EnvSetup
					.getData("SellerId"));
			
//			List<String> skuList = agentProduct.getCatalogList();
			List<String> skuList = Arrays.asList("c2443402", "c2443403");

			//修改stock
			Map<String, Object> skuAndStockMap = generateSKUStock(skuList);

			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			for (String key : skuAndStockMap.keySet()) {
				try {
					SkuStock skuStock = new SkuStock();
					skuStock.setOuter_sku_id("outer" + key);
					skuStock.setStock_num(Integer.parseInt(skuAndStockMap.get(
							key).toString()));
					skuStock.setSku_id(key);

					skuStocks.add(skuStock);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			v1updateproductstockBean.setSku_stocks(skuStocks);

			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(sellerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			JSONObject retBean = new JSONObject(
					shenqiUpdateProductStockCall.getReturnData());

			Logger.verifyEquals("0000", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

			JSONArray jsonArray = retBean.getJSONObject("content")
					.getJSONArray("results");

			for (int j = 0; j < jsonArray.length(); j++) {

				Logger.verifyEquals(false, jsonArray.getJSONObject(j)
						.getBoolean("success"), "返回报文检查");
				Logger.verifyEquals("sku_id无效", jsonArray.getJSONObject(j)
						.getString("msg"), "返回报文msg检查");
			}
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_008() {
		Logger.start(true, "根据sku_id更新货头商品库存");
		try {
			AgentProductBean agentProductBean = DGSQBuildProxyChainCallService
					.createProxychain((int)autotest_goodsOwnerId, 0, false);
			
			List<String> skuList = agentProductBean.getCatalogList();

			//修改stock
			Map<String, Object> skuAndStockMap = generateSKUStock(skuList);

			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			for (String key : skuAndStockMap.keySet()) {
				try {
					SkuStock skuStock = new SkuStock();
					skuStock.setOuter_sku_id("outer" + key);
					skuStock.setStock_num(Integer.parseInt(skuAndStockMap.get(
							key).toString()));
					skuStock.setSku_id(key);

					skuStocks.add(skuStock);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			v1updateproductstockBean.setSku_stocks(skuStocks);
			v1updateproductstockBean.setOperate_id(TestDataManager.getRandomUUID().toString());
//			v1updateproductstockBean.setOperate_id("0cafdbd8-60e2-4e2f-ae1f-9e73ca167c49");
			
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(autotest_goodsOwnerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			JSONObject retBean = new JSONObject(
					shenqiUpdateProductStockCall.getReturnData());

			Logger.verifyEquals("0000", shenqiUpdateProductStockCall.getCode(),
					"验证Code");

			this.checkStockBySku(retBean.getJSONObject("content")
					.getJSONArray("results"), skuAndStockMap);
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings("static-access")
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_sqUpdateProductStock_009() {
		Logger.start(true, "operate_id重复，更新失败");
		try {
			
			List<String> skuList = Arrays.asList("c9293865", "c9293864");

			//修改stock
			Map<String, Object> skuAndStockMap = generateSKUStock(skuList);

			List<SkuStock> skuStocks = new ArrayList<SkuStock>();

			for (String key : skuAndStockMap.keySet()) {
				try {
					SkuStock skuStock = new SkuStock();
					skuStock.setOuter_sku_id("outer" + key);
					skuStock.setStock_num(Integer.parseInt(skuAndStockMap.get(
							key).toString()));
					skuStock.setSku_id(key);

					skuStocks.add(skuStock);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			v1updateproductstockBean.setSku_stocks(skuStocks);
			v1updateproductstockBean.setOperate_id("0cafdbd8-60e2-4e2f-ae1f-9e73ca167c49");
			
			OpenApiWapper openApiWapper = new OpenApiWapper();

			Application application = openApiWapper
					.selectApplicationBySellerId(autotest_goodsOwnerId).get(0);

			String app_id = application.getApp_id();
			String app_secret = application.getApp_secret();

			AuthCode authCode = openApiWapper.selectAuthCodeByAppId(app_id)
					.get(0);

			openapiReq.setApp_id(app_id);
			openapiReq.setSign_method("MD5");
			openapiReq.setAuth_code(authCode.getAuth_code());
			openapiReq.setTimestamp(YMTDateUtil.getSysTime());
			openapiReq.setNonce_str(TestDataManager.getRandomNum(31));
			openapiReq.setBiz_content(new FormatUtil()
					.beanToGSONString(v1updateproductstockBean));
			openapiReq.setSign(OpenapiService.generateMD5(openapiReq,
					AesUtil.decrypt(app_secret)));

			String url = String
					.format("http://apigateway.ymatou.com/apigateway/v1?app_id=%s&method=sq.sku.stock.update",
							app_id);
			shenqiUpdateProductStockCall.setUrl(url);

			shenqiUpdateProductStockCall.setData(openapiReq);
			shenqiUpdateProductStockCall.callService();

			Logger.verifyEquals("0009", shenqiUpdateProductStockCall.getCode(),
					"验证Code");
			Logger.verifyEquals("重复操作", shenqiUpdateProductStockCall.getMessage(),
					"验证message");
			
		} catch (Exception e) {
			Logger.fail(e);
		}
	}
	
	public static void main(String[] args) throws Exception {
		
		Ts_sqUpdateProductStock test = new Ts_sqUpdateProductStock();
		
		Map<String, Object> skuIdandStockMap = new HashMap<>();
		
		skuIdandStockMap.put("c9277707", 71);
		skuIdandStockMap.put("c9277706", 95);
		
		JSONObject retBean = new JSONObject(
				"{\"code\":\"0000\",\"message\":\"操作成功\",\"content\":{\"needPrintLog\":true,\"results\":"
				+ "[{\"msg\":null,\"outer_sku_id\":\"outerc9277707\",\"success\":true,\"sku_id\":\"c9277707\","
				+ "\"sub_code_id\":null},{\"msg\":null,\"outer_sku_id\":\"outerc9277706\",\"success\":true,"
				+ "\"sku_id\":\"c9277706\",\"sub_code_id\":null}]}}");
		
		JSONArray skuResults = retBean.getJSONObject("content")
				.getJSONArray("results");
		
		test.checkStockBySku(skuResults, skuIdandStockMap);
	}
}